package com.tencent.shadow.sample.host.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.mcsappframework.utils.SharePreferenceUtil;
import com.tencent.shadow.sample.host.MainActivity;
import com.tencent.shadow.sample.host.R;
import com.tencent.shadow.sample.host.common.APIWEBSERVICE;
import com.tencent.shadow.sample.host.common.MCode;
import com.tencent.shadow.sample.host.model.UserInfo;
import com.tencent.shadow.sample.host.ui.common.BaseActivity;

import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


public class InitActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    private final int PERMISSION_REQUEST_CODE = 102;

    String[] permissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA,
    };

    @Override
    protected void setDataBindingContentView() {
        DataBindingUtil.setContentView(this, R.layout.activity_init);
        checkPermission();
    }

    @Override
    protected void init() {

    }

    private void into() {
        String userInfo =  util.getString(SharePreferenceUtil.PREFERENCES_USERINFO);
        //之前没序列化userinfo导致增删字段反序列话失败，让用户重新登陆
        if (userInfo == null) {
            util.remove(SharePreferenceUtil.PREFERENCES_AUTHKEY);
        }
        CountDownTimer timer = new CountDownTimer(1000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                String Authkey = null;
                if (!"https://sfa.eyili.com/".equals(APIWEBSERVICE.REMOTE_MCSWSIAPI)) {//如果不是测试地址
                    String remote = util.getStringValue(MCode.PREFERENCES_REMOTE);  //读取保存的网络设置地址
                    if (!TextUtils.isEmpty(remote)) {
                        APIWEBSERVICE.REMOTE_MCSWSIAPI = remote;  //此时BaseManager未初始化，更改请求地址
                    }
                }
                try {
                    Authkey = (String) util.getCacheValue(SharePreferenceUtil.PREFERENCES_AUTHKEY);
                    Log.d("authkry", "addObserver: " + util.getCacheValue(SharePreferenceUtil.PREFERENCES_AUTHKEY));
                } catch (Exception e) {
                    util.remove(SharePreferenceUtil.PREFERENCES_AUTHKEY);
                    e.printStackTrace();
                }
                if (Authkey != null && Authkey.length() == 36 && !TextUtils.isEmpty(util.getStringValue(SharePreferenceUtil.PREFERENCES_PASSWORD)) && TextUtils.isEmpty(util.getStringValue("sly"))) {
                    openActivity(MainActivity.class);
                } else {
                    openActivity(LoginActivity.class);
                }
                overridePendingTransition(0, 0);
                close();
            }
        };
        timer.start();
    }

    @AfterPermissionGranted(PERMISSION_REQUEST_CODE)
    private void checkPermission() {

        if (!EasyPermissions.hasPermissions(this, permissions)) {
            EasyPermissions.requestPermissions(this, "当前需要用户允许必要的权限！", PERMISSION_REQUEST_CODE, permissions);
        } else {
            into();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        into();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        showWaringDialog();
    }

    private void showWaringDialog() {
        new AppSettingsDialog.Builder(this)
                .setTitle("无相关权限")
                .setRationale("可能会导致登录人信息无法验证,前往设置打开权限")
                .setPositiveButton("前往设置")
                .setNegativeButton("取消")
                .setRequestCode(PERMISSION_REQUEST_CODE)//用于onActivityResult回调做其它对应相关的
                .build().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (!EasyPermissions.hasPermissions(this, permissions)) {
                    if (!EasyPermissions.hasPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,})) {
                        MessageTools.showShortToast("存储权限未被允许！");
                    }
                    if (!EasyPermissions.hasPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE})) {
                        MessageTools.showShortToast("电话权限未被允许！");
                    }

                    if (!EasyPermissions.hasPermissions(this, new String[]{Manifest.permission.CAMERA})) {
                        MessageTools.showShortToast("相机权限未被允许！");
                    }
                    finish();
                }
                break;
            default:
        }
    }

}
